import { Component, Input, OnChanges, OnInit } from '@angular/core'
import { FormArray, FormBuilder, Validators } from '@angular/forms'
import { Address, Hero, states } from '../data-model'

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit, OnChanges {
  @Input() hero: Hero

  heroForm
  states = states

  get secretLairs(): FormArray {
    return this.heroForm.get('secretLairs') as FormArray
  }

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.createForm3()
    this.logNameChange()
  }

  ngOnChanges() {
    this.heroForm.reset({
      name: this.hero.name,
      address: this.hero.addresses[ 0 ] || new Address()
    })
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: [ '', Validators.required ],
      address: this.fb.group({
        street: '',
        city: '',
        state: '',
        zip: '',
      }),
      power: '',
      sidekick: ''
    })
  }

  createForm2() {
    this.heroForm = this.fb.group({
      name: [ '', Validators.required ],
      address: this.fb.group(new Address()),
      power: '',
      sidekick: ''
    })
  }

  createForm3() {
    this.heroForm = this.fb.group({
      name: [ '', Validators.required ],
      secretLairs: this.fb.array([]),
      power: '',
      sidekick: ''
    })
  }

  setAddress(addresses: Address[]) {
    const addressFGs = addresses.map(addr => this.fb.group(addr))
    const addressFormArray = this.fb.array(addressFGs)
    this.heroForm.setControl('secretLairs', addressFormArray)
  }

  addLair() {
    this.secretLairs.push(this.fb.group(new Address()))
  }

  private nameChangeLog: string[] = []

  logNameChange() {
    const nameControl = this.heroForm.get('name')
    nameControl.valueChanges.forEach((v: string) => this.nameChangeLog.push(v))
  }
}
